﻿using System;
using System.Diagnostics.Tracing;
using System.Threading;

namespace Sustainalytics.EsgRatings.BusinessLogic
{
    [EventSource(Name = "Sustainalytics-ESGRatings")]
    public sealed class EsgRatingsEventSource : EventSource
    {
        private static Lazy<EsgRatingsEventSource> _lazyLog = new Lazy<EsgRatingsEventSource>(InitLog, LazyThreadSafetyMode.ExecutionAndPublication);

        public static EsgRatingsEventSource Log => _lazyLog.Value;

        [NonEvent]
        private static EsgRatingsEventSource InitLog()
        {
            var log = new EsgRatingsEventSource();
            log.Ping();

            return log;
        }

        [Event(1, Level = EventLevel.LogAlways)]
        public void Ping()
        {
            if (IsEnabled())
            {
                WriteEvent(1);
            }
        }

        [Event(101, Task = Tasks.EsgRatingsImport, Opcode = EventOpcode.Start, Level = EventLevel.Informational, Message = "ESGRatingsImport/Start")]
        public void ImportEsgRatingsStart(int dataFileBytes)
        {
            if (IsEnabled())
            {
                WriteEvent(101, dataFileBytes);
            }
        }

        [Event(102, Task = Tasks.EsgRatingsImport, Opcode = EventOpcode.Stop, Level = EventLevel.Informational, Message = "ESGRatingsImport/Stop")]
        public void ImportEsgRatingsStop(int dataFileBytes)
        {
            if (IsEnabled())
            {
                WriteEvent(102, dataFileBytes);
            }
        }

        [Event(103, Level = EventLevel.Error, Message = "ESGRatingsImport/Failed")]
        public void ImportEsgRatingsFailed(int dataFileBytes, string exceptionType, string exceptionMessage, string exceptionInformation)
        {
            if (IsEnabled())
            {
                WriteEvent(103, dataFileBytes, exceptionType, exceptionMessage, exceptionInformation);
            }
        }

        [Event(104, Task = Tasks.EsgRatingsImport, Level = EventLevel.Informational, Message = "ESGRatingsImport/Succeeded")]
        public void ImportEsgRatingsSucceeded(int dataFileBytes, string errorsLog, string warningsLog, string infoLog)
        {
            if (IsEnabled())
            {
                WriteEvent(104, dataFileBytes, errorsLog, warningsLog, infoLog);
            }
        }

        [Event(3, Level = EventLevel.Error)]
        public void LogException(string msg)
        {
            if (!IsEnabled()) return;
            WriteEvent(3, msg);
        }

        [NonEvent]
        public void LogException(Exception ex)
        {
            LogException(ex.ToString());
        }

        public class Tasks
        {
            public const EventTask EsgRatingsImport = (EventTask)0x1;// > 0
        }
    }
}
